function [Mdl, imp, Yfit, Sfit] = trainRF(pred, resp, NumTrees, str_method)

% returns a ensemble of NumTrees bagged classification trees trained 
% using the data in pred(X). resp is the name of the response variable 
% in pred.
%
% str_method refers to either 'classification' or 'regression'. 
% Regression requires a numeric Y.

% fix the initial random seed
rng('default'); % For reproducibility

Mdl = TreeBagger(NumTrees, pred, resp, 'Method', str_method, ...
    'Surrogate', 'on', 'OOBPredictorImportance', 'on');

% compute predictor importance estimates
imp = Mdl.OOBPermutedPredictorDeltaError;

% Ensemble predictions for out-of-bag observations
[Yfit,Sfit] = oobPredict(Mdl);

end
